package net.sdd.school.controller;


import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sdd.common.result.Result;
import net.sdd.school.entity.Video;
import net.sdd.school.service.IVideoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author Jet
 * @since 2022-08-23
 */
@RestController
@RequestMapping("/sddonline/video")
@Slf4j
public class VideoController {
    @Autowired
    private IVideoService videoService;
    @Autowired
    private RestTemplate restTemplate;


    @ApiOperation("根据id查询视频")
    @GetMapping("/{id}")
    public Result findById(@PathVariable("id")String id) {
        Video chapter = videoService.getById(id);
        return Result.ok().data("video",chapter);
    }

    @ApiOperation("修改视频")
    @PutMapping
    public Result update(@RequestBody Video video) {
        videoService.updateById(video);
        return Result.ok();
    }

    @ApiOperation("添加视频")
    @PostMapping
    public Result add(@RequestBody Video video) {
        videoService.save(video);
        return Result.ok();
    }


    @ApiOperation("删除视频")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id")String id) {
        // 获取当前时间的毫秒
        long start = System.currentTimeMillis();
        log.info("执行删除视频开始：{}", start);

        // 1、先查询获取videoId（阿里云上的视频唯一标记）
        Video video = videoService.getById(id);
        String videoId = video.getVideoSourceId();
        // 2、删除视频
        videoService.removeById(id);

        // 创建一个线程
        new Thread(()->{
            // 3、删除阿里云视频 (远程调用)
            String url = "http://localhost:8030/vod/video/" + videoId;
            restTemplate.delete(url);
        }).start(); // start表示执行线程

        log.info("执行删除视频结束，用时：{}",(System.currentTimeMillis() - start));

        return Result.ok();
    }
}

